package com.wy.navigator;

import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.xml.*;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class FacadeInvokeLineMarkerProvider extends RelatedItemLineMarkerProvider {

    @Override
    protected void collectNavigationMarkers(@NotNull PsiElement element, @NotNull Collection<? super RelatedItemLineMarkerInfo<?>> result) {
        // 检查是否为XML标签元素
        if (!(element instanceof XmlTag)) {
            return;
        }
        XmlTag currentTag = (XmlTag) element;

        // 检查当前文件是否为biz-context-开头的xml文件,
        // 检查是否为bean标签且class属性匹配目标类
        PsiFile containingFile = element.getContainingFile();
        String fileName = containingFile.getName();
        if (!fileName.startsWith("biz-context-") || !fileName.endsWith(".xml") || !"bean".equals(currentTag.getLocalName())) {
            return;
        }

        XmlAttribute classAttr = currentTag.getAttribute("class");
        if (classAttr == null ) {
            return;
        }

        if(!JSearchUtils.endWith(classAttr.getValue(),Constants.TARGET_CLASS_LIST)) {
            Project project = element.getProject();
            PsiClass targetClass = JavaPsiFacade.getInstance(project)
                            .findClass(classAttr.getValue(), GlobalSearchScope.allScope(project));

            if (targetClass == null) {
                return;
            }

            NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder
                    .create(JIcons.ToJava)
                    .setTargets(targetClass)
                    .setTooltipText("Navigate to facade target class");

            result.add(builder.createLineMarkerInfo(currentTag));

        }else{
            // 查找name为facadeTarget的property子标签
            XmlTag[] propertyTags = currentTag.findSubTags("property");
            String facadeTargetValue = null;
            for (XmlTag propertyTag : propertyTags) {
//            XmlAttribute nameAttr = propertyTag.getAttribute("name");
//            if (nameAttr != null && PROPERTY_NAME.equals(nameAttr.getValue())) {
//                XmlAttribute valueAttr = propertyTag.getAttribute("value");
//                if (valueAttr != null) {
//                    facadeTargetValue = valueAttr.getValue();
//                    break;
//                }
//            }
                facadeTargetValue = propertyTag.getSubTags()[0].getValue().getTrimmedText();
                break;
            }

            if (facadeTargetValue == null || !facadeTargetValue.contains("!")) {
                return;
            }

            // 解析获取目标bean的id
            String targetBeanId = facadeTargetValue.split("!")[0];
            if (targetBeanId.isEmpty()) {
                return;
            }

            String methodName = facadeTargetValue.split("!")[1];
            if (methodName.isEmpty()) {
                return;
            }

            // 在当前XML中查找目标bean标签
            XmlDocument document = (XmlDocument) containingFile.getFirstChild();
            if (document == null) {
                return;
            }
            XmlTag rootTag = document.getRootTag();
            if (rootTag == null) {
                return;
            }

            XmlTag targetBeanTag = findTargetBeanTag(rootTag, targetBeanId);
            if (targetBeanTag == null) {
                return;
            }

            // 获取目标bean的class属性值
            XmlAttribute targetClassAttr = targetBeanTag.getAttribute("class");
            if (targetClassAttr == null || targetClassAttr.getValue() == null) {
                return;
            }
            String targetClassName = targetClassAttr.getValue();

            // 查找目标类
            Project project = element.getProject();
            PsiClass targetClass = JavaPsiFacade.getInstance(project)
                    .findClass(targetClassName, GlobalSearchScope.allScope(project));

            List<PsiMethod> methods =
                    Arrays.stream(targetClass.getAllMethods())
                            .filter(method -> method.getName().equals(methodName))
                            .distinct()
                            .toList();


            if (!methods.isEmpty()) {
                // 创建跳转图标
                NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder
                        .create(JIcons.ToJava)
                        .setTargets(methods)
                        .setTooltipText("Navigate to facade target class");

                result.add(builder.createLineMarkerInfo(currentTag));
            }

            System.out.println(result);
        }

    }

    /**
     * 递归查找目标bean标签
     */
    private XmlTag findTargetBeanTag(XmlTag parentTag, String targetBeanId) {
        // 检查当前标签是否为目标bean
        if ("bean".equals(parentTag.getLocalName())) {
            XmlAttribute idAttr = parentTag.getAttribute("id");
            if (idAttr != null && targetBeanId.equals(idAttr.getValue())) {
                return parentTag;
            }
        }

        // 递归查找子标签
        XmlTag[] subTags = parentTag.getSubTags();
        for (XmlTag subTag : subTags) {
            XmlTag result = findTargetBeanTag(subTag, targetBeanId);
            if (result != null) {
                return result;
            }
        }

        return null;
    }
}